import socket
import network
import os
import time
import machine

from machine import ADC
from machine import Timer
import dht
from machine import I2C

dh = dht.DHT11(machine.Pin(16))

adc0=ADC(0) 
SSID="zd"                                            #修改为你的WiFi名字
PASSWORD="19991013"                                       #WIFI密码
port=9001
wlan=None
listenSocket=None
ip=""
def connectWifi(ssid, passwd):  
  wlan=network.WLAN(network.STA_IF)                        #创建一个wlan对象
  wlan.active(True)                                        #激活网络接口
  wlan.disconnect()                                        #断开上次的WiFi连接
  wlan.connect(ssid,passwd)
  
  while(wlan.ifconfig()[0] == '0.0.0.0'):
    time.sleep(1)
  ip=wlan.ifconfig()[0]
  return True

connectWifi(SSID, PASSWORD)

listenSocket = socket.socket() #建立一个实例

listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

listenSocket.bind((ip,port))  #绑定建立网路连接的ip地址和端口

listenSocket.listen(5) #开始侦听

print ('tcp waiting...')

while True:

  print("accepting.....")
  try:
    conn, addr = listenSocket.accept()
    while True:
      dh.measure()
      temp=dh.temperature()
      hum=dh.humidity()
      d3=str(hum)+","+str(temp)+","+str(adc0.read()*0.1)
      d3=d3.replace("\'","\"")
      mes1=d3.encode('utf-8')
      conn.send(mes1)
      print(mes1)
      time.sleep(1.0)
      
  finally:
    print("Not Connection!")







